const fs = require('fs').promises;
const path = require('path');
const { pipeline } = require('stream/promises');

// 确保目标目录存在
const targetDir = path.join(__dirname, '../client/public/assets/media');

async function downloadFile(url, filePath, index) {
    try {
        // 检查文件是否已存在且非空
        try {
            const stats = await fs.stat(filePath);
            if (stats.size > 0) {
                console.log(`SOUND ${index}.mp3 already exists, skipping...`);
                return true;
            }
        } catch (err) {
            // 文件不存在，继续下载
        }

        const res = await fetch(url);
        
        if (res.status === 200) {
            console.log(`Downloading SOUND ${index}.mp3...`);
            
            const fileStream = require('fs').createWriteStream(filePath);
            await pipeline(res.body, fileStream);
            
            console.log(`Downloaded SOUND ${index}.mp3 successfully`);
            
            // 检查文件大小，如果为0则删除文件
            const stats = await fs.stat(filePath);
            if (stats.size === 0) {
                await fs.unlink(filePath);
                console.log(`Removed empty file: SOUND ${index}.mp3`);
                return false;
            }
            
            return true;
        } else {
            console.log(`Failed to download SOUND ${index}.mp3 - Status: ${res.status}`);
            return false;
        }
    } catch (err) {
        console.error(`Error downloading SOUND ${index}.mp3:`, err.message);
        // 出错时删除可能创建的损坏文件
        try {
            await fs.unlink(filePath);
        } catch (unlinkErr) {
            // 忽略删除错误
        }
        return false;
    }
}

async function main() {
    try {
        // 确保目标目录存在
        await fs.mkdir(targetDir, { recursive: true });
        
        let downloadedCount = 0;
        const maxConcurrent = 5; // 限制并发数
        const downloadQueue = [];
        
        for (let i = 1; i < 50; i++) {
            const url = `https://thesoundofenglish.org/wp-content/uploads/in5-archives/interactive-ipa-chart-22/Interactive IPA Chart 22/assets/media/SOUND ${i}.mp3`;
            const filePath = path.join(targetDir, `SOUND ${i}.mp3`);
            
            const downloadPromise = downloadFile(url, filePath, i).then(success => {
                if (success) downloadedCount++;
            });
            
            downloadQueue.push(downloadPromise);
            
            // 控制并发数
            if (downloadQueue.length >= maxConcurrent) {
                await Promise.all(downloadQueue.splice(0, maxConcurrent));
            }
        }
        
        // 等待剩余的下载完成
        await Promise.all(downloadQueue);
        
        console.log(`\nDownload complete. Total files downloaded: ${downloadedCount}`);
    } catch (err) {
        console.error('Error in main process:', err);
    }
}

main();